import { db } from '../database/db';
import { GCategoryDesc } from '../domain/g_category_desc';

export async function getCategoryDescList(offset = 0, limit = 10) {
    const baseQuery = db.selectFrom('g_category_desc');
    const [{ count }] = await baseQuery.select(db.fn.countAll().as('count')).execute();
    const total = Number(count);
    if (total === 0) {
        return { list: [], total: 0 };
    }
    const list = await baseQuery
        .selectAll()
        .orderBy('id', 'asc')
        .offset(offset)
        .limit(limit)
        .execute();
    return { list, total };
}

export async function getCategoryDescById(id: number) {
    return await db.selectFrom('g_category_desc')
        .selectAll()
        .where('id', '=', id)
        .executeTakeFirst();
}

export async function getCategoryDescByAlias(alias: string) {
    return await db.selectFrom('g_category_desc')
        .selectAll()
        .where('alias', '=', alias)
        .execute();
}

export async function createCategoryDesc(data: GCategoryDesc) {
    const result = await db.insertInto('g_category_desc').values(data as any).executeTakeFirst();
    return Number((result as any).insertId);
}

export async function updateCategoryDesc(id: number, data: Partial<GCategoryDesc>) {
    const result = await db.updateTable('g_category_desc')
        .set(data)
        .where('id', '=', id)
        .executeTakeFirst();
    return result.numUpdatedRows;
}

export async function deleteCategoryDesc(id: number) {
    // 物理删除，如需逻辑删除可自行扩展
    const result = await db.deleteFrom('g_category_desc')
        .where('id', '=', id)
        .executeTakeFirst();
    return result.numDeletedRows;
} 